#
# DailyLiveSnap.Options
#

__all__ = ['parse', 'ArgumentParseError']

import sys

from DailyLiveSnap import Command
from DailyLiveSnap.NLS import _

class ArgumentParseError(Exception):
    pass

def reorder_args(argv):
    # reorders argv list so that one non-option appear first for `command'.
    args = argv[1:]
    nonopts = [i for i, arg in enumerate(args) if not arg.startswith('-')]
    if not nonopts:
        return [argv[0]] # command is not specified.

    restargs = args[:]
    cmd = restargs.pop(min(nonopts))
    return [argv[0], cmd] + restargs

def parse(argv):
    try:
        if len(argv) < 2:
            raise ArgumentParseError

        argv = reorder_args(argv)
        cmd = argv[1]

        if cmd not in Command.COMMANDS and cmd not in Command.ALIASES:
            print >> sys.stderr, _("Unknown command: '%s'") % cmd
            raise ArgumentParseError

        cmdcls = Command.load_command(cmd)
        return cmdcls, cmdcls.parse_options(argv[2:])

    except ArgumentParseError:
        print >> sys.stderr, _("Type '%s help' for usage.") % argv[0]
        return None, None
